package com.ck.util;

import com.ck.constant.NormalStrConstant;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * 文件工具类
 *
 * @author dxy
 * @date 2018/7/3 14:07
 */
public class FileUtils {

    /**
     * 读取文件
     *
     * @param path 路径
     * @return
     */
    public static String readFile(String path) {
        StringBuffer laststr = new StringBuffer("");
        File file = new File(path);// 打开文件
        BufferedReader reader = null;
        FileInputStream in = null;
        try {
            in = new FileInputStream(file);
            reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));// 读取文件
            String tempString = null;
            while ((tempString = reader.readLine()) != null) {
                laststr.append(tempString);
            }
            reader.close();
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException el) {
                }
            }
            if (in != null) {
                try {
                    in.close();
                } catch (IOException el) {
                }
            }
        }
        return laststr.toString();
    }

    /**
     * 保存文件
     *
     * @param url
     * @param name
     * @param retry
     */
    public static void saveUrlAs(String url, String name, int retry) throws UnsupportedEncodingException {
        if (retry <= 0) {
            return;
        }
        //json文件存放目录
        String jsonFilePath = PropertyFileUtils.getPropertyValueByKey("application-dev", "custom.json-file-save-path");
        File file = new File(jsonFilePath);
        //判断文件夹是否存在
        if (!file.exists()) {
            //如果文件夹不存在，则创建新的的文件夹
            file.mkdirs();
        }
        FileOutputStream fileOut = null;
        HttpURLConnection conn = null;
        InputStream inputStream = null;
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            // 建立链接
            URL httpUrl = new URL(url);
            conn = (HttpURLConnection) httpUrl.openConnection();
            //以Post方式提交表单，默认get方式
            conn.setRequestMethod("GET");
            conn.setDoInput(true);
            conn.setDoOutput(true);
            // post方式不能使用缓存
            conn.setUseCaches(false);
            //连接指定的资源
            conn.connect();
            //获取网络输入流
            inputStream = conn.getInputStream();
            bis = new BufferedInputStream(inputStream);
            //判断文件的保存路径后面是否以/结尾
            if (!jsonFilePath.endsWith(NormalStrConstant.SLASH)) {

                jsonFilePath += NormalStrConstant.SLASH;

            }
            //写入到文件（注意文件保存路径的后面一定要加上文件的名称）
            fileOut = new FileOutputStream(jsonFilePath + name);
            bos = new BufferedOutputStream(fileOut);

            byte[] buf = new byte[1024];
            int length = bis.read(buf);
            //保存文件
            while (length != -1) {
                bos.write(buf, 0, length);
                length = bis.read(buf);
            }
        } catch (Exception e) {
            e.printStackTrace();
            saveUrlAs(url, name, retry - 1);
        } finally {
            try {
                if (bos != null) {
                    bos.close();
                }
                if (bis != null) {
                    bis.close();
                }
                if (fileOut != null) {
                    fileOut.close();
                }
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (conn != null) {
                conn.disconnect();
            }
        }
    }

    /**
     * MultipartFile转化为File
     *
     * @param multipartFile MultipartFile
     * @return File
     * @throws IOException
     */
    public static File multipartFileConvertFile(MultipartFile multipartFile) throws IOException {
        if (multipartFile == null) {
            throw new NullPointerException("文件不能为空");
        }
        File file = new File(multipartFile.getOriginalFilename());
        file.createNewFile();
        //自动关闭流
        try (FileOutputStream fos = new FileOutputStream(file)) {
            fos.write(multipartFile.getBytes());
        }
        return file;
    }

    /**
     * MultipartFile转化为File
     *
     * @param multipartFile MultipartFile
     * @return File
     * @throws IOException
     */
    public static File multipartFileConvertFile(MultipartFile multipartFile, String fileName) throws IOException {
        if (multipartFile == null) {
            throw new NullPointerException("文件不能为空");
        }
        File file = null;
        if (fileName != null && fileName != "") {
            file = new File(fileName);
        } else {
            file = new File(multipartFile.getOriginalFilename());
        }
        try (FileOutputStream fos = new FileOutputStream(file)) {
            fos.write(multipartFile.getBytes());
        }
        return file;
    }

    /**
     * 获取文件MD5值
     *
     * @param filePath String
     * @return String
     */
    public static String getFileMD5(String filePath) {
        File file = new File(filePath);
        if (file.exists() && file.isFile()) {
            try {
                MessageDigest messageDigest = MessageDigest.getInstance("MD5");
                InputStream in = new FileInputStream(file);
                byte[] cache = new byte[1024];
                int nRead = 0;
                while ((nRead = in.read(cache)) != -1) {
                    messageDigest.update(cache, 0, nRead);
                }
                in.close();
                byte[] data = messageDigest.digest();
                return byteToHex(data);
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return "";
    }

    /**
     * 获取文件MD5值
     *
     * @param file File
     * @return String
     */
    public static String getFileMD5(File file) {
        String md5 = "";
        if (file.exists() && file.isFile()) {
            try {
                MessageDigest md = MessageDigest.getInstance("MD5");
                InputStream in = new FileInputStream(file);
                byte[] buffer = new byte[1024];
                int read = 0;
                while ((read = in.read(buffer)) != -1) {
                    md.update(buffer, 0, read);
                }
                in.close();
                byte[] data = md.digest();
                md5 = byteToHex(data);
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return md5;
    }

    /**
     * byte转化为16进制字符串
     *
     * @param bytes byte[]
     * @return String
     */
    private static String byteToHex(byte[] bytes) {
        char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                'a', 'b', 'c', 'd', 'e', 'f'};
        StringBuffer stringbuffer = new StringBuffer(2 * bytes.length);
        for (byte b : bytes) {
            char c0 = hexDigits[b >>> 4 & 0xf];
            char c1 = hexDigits[b & 0xf];
            stringbuffer.append(c0);
            stringbuffer.append(c1);
        }
        return stringbuffer.toString();
    }

    /**
     * TODO 读取文件(导入JSON文件发布广告测试)
     *
     * @param multipartFile
     * @return
     */
    public static String readFile(MultipartFile multipartFile) throws IOException {
        StringBuffer laststr = new StringBuffer("");
//		File file = multipartFileConvertFile(multipartFile);
        File file = new File(multipartFile.getOriginalFilename());
        //自动关闭流
        try (FileOutputStream fos = new FileOutputStream(file)) {
            fos.write(multipartFile.getBytes());
        }
        BufferedReader reader = null;
        FileInputStream in = null;
        try {
            in = new FileInputStream(file);
            reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));// 读取文件
            String tempString = null;
            while ((tempString = reader.readLine()) != null) {
                laststr.append(tempString);
            }
            reader.close();
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException el) {
                }
            }
            if (in != null) {
                try {
                    in.close();
                } catch (IOException el) {
                }
            }
            if (null != file) {
                file.delete();
            }
        }
        return laststr.toString();
    }

    /**
     * 从网路地址中获取文件
     *
     * @param downloadStie 下载地址
     * @param dest         文件存储全路径
     * @throws IOException
     */
    public static void downloadFileFromURL(String downloadStie, String dest) throws IOException {
        if (StringUtils.isBlank(downloadStie) || StringUtils.isBlank(dest)) {
            throw new NullPointerException("");
        }
        File tempFile = new File(dest);
        //如果文件父目录不存在，就创建文件父目录
        if (!tempFile.getParentFile().exists()) {
            tempFile.getParentFile().mkdirs();
            System.out.println("创建文件夹：" + dest);
        }
        URL url = new URL(downloadStie);
        try (ReadableByteChannel rbc = Channels.newChannel(url.openStream()); FileOutputStream fos = new FileOutputStream(tempFile)) {
            fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
        }
    }


    /**
     * 删除路径下所有文件
     *
     * @param path
     * @return
     */
    public static boolean delAllFile(String path) {
        boolean flag = false;
        File file = new File(path);
        if (!file.exists()) {
            return false;
        }
        if (!file.isDirectory()) {
            return false;
        }
        String[] tempList = file.list();
        File temp = null;
        for (String aTempList : tempList) {
            if (path.endsWith(File.separator)) {
                temp = new File(path + aTempList);
            } else {
                temp = new File(path + File.separator + aTempList);
            }
            if (temp.isFile()) {
                temp.delete();
            }
            if (temp.isDirectory()) {
                //先删除文件夹里面的文件
                delAllFile(path + "/" + aTempList);
                //再删除空文件夹
                delFolder(path + "/" + aTempList);
                flag = true;
            }
        }
        flag = file.delete();
        return flag;
    }

    private static void delFolder(String folderPath) {
        try {
            delAllFile(folderPath);
            String filePath = folderPath;
            File myFilePath = new File(filePath);
            //删除空文件夹
            myFilePath.delete();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
